<?php

namespace mpend\modules\cms\models;

use Yii;
use yii\db\Exception;
use common\models\cms\CmsArticle;
use common\models\cms\CmsArticleLike;

/**
 * 资讯点赞模型
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ArticleLikeForm extends \common\base\Model {

    /**
     * @var integer 用户ID
     */
    public $user_id;

    /**
     * @var integer 资讯ID
     */
    public $article_id;

    /**
     * @var CmsArticle 资讯
     */
    private $_article;

    /**
     * @return array validation rules
     */
    public function rules() {
        return [
            [['user_id', 'article_id'], 'integer'],
            [['article_id'], 'required'],
            [['article_id'], 'validateArticle'],
        ];
    }

    /**
     * 校验文章是否存在
     * @param string $attribute the attribute currently being validated
     */
    public function validateArticle($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $model = CmsArticle::find()->active(CmsArticle::STATUS_ACTIVE)->where([
            'id' => $this->$attribute,
        ])->one();
        if (!$model) {
            return $this->addError($attribute, '资讯内容不存在');
        }
        $this->_article = $model;
    }

    /**
     * @return CmsArticle|null
     */
    public function getArticle() {
        return $this->_article;
    }

    /**
     * 保存动态点赞信息
     * @return boolean
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('点赞操作参数校验失败');
        }
        $article = $this->getArticle();
        $likes = $article->likes;
        $model = CmsArticleLike::findOrNew($this->attributes);
        $liked = false;
        if ($model->isNewRecord) {
            $liked = true;
            $likes += 1;
        } else {
            $likes -= 1;
        }
        if ($likes < 0) {
            $likes = 0;
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if ($liked) {
                if (!$model->save()) {
                    throw new Exception($model->getErrorMsg());
                }
            } else {
                if (!$model->delete()) {
                    throw new Exception($model->getErrorMsg());
                }
            }
            $article->likes = $likes;
            $article->weight = $likes + $article->views;
            if (!$article->save()) {
                throw new Exception($article->getErrorMsg());
            }
            $transaction->commit();
        } catch (Exception $e) {
            // 记录回滚（事务回滚）
            $transaction->rollBack();
            return $this->dumpError($e->getMessage());
        }
        return $liked;
    }

}
